package com.im.sdk.android;

import com.im.common.*;
import com.im.protocol.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

/**
 * @Created leijun
 * @Date 2021/9/11 8:14 上午
 */
public class ImClientHandler extends ChannelInboundHandlerAdapter {

    private ImClient imClient;

    public ImClientHandler(ImClient imClient) {
        this.imClient = imClient;
    }

    /**
     * 与接入层断开连接会调用这个方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 从zk中重新选择一个接入系统重新连接
        imClient.reconnect();
    }

    /**
     * 接收到接入层的请求
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = new Message((ByteBuf) msg);
        if (ImConstant.MESSSAGE_TYPE_RESPONSE == message.getMessageType()) {
            Response response = message.toResponse();
            if (ImConstant.REQUEST_TYPE_AUTHENTICATE == message.getRequestType()) {
                AuthenticateResponseProto.AuthenticateResponse authenticateResponse =
                        AuthenticateResponseProto.AuthenticateResponse.parseFrom(response.getBody());
                if (authenticateResponse.getErrorCode() == ResponseCode.OK) {
                    if (authenticateResponse.getStatus() == ResponseCode.OK) {
                        System.out.println("认证成功！");
                    } else {
                        System.out.println("认证失败！");
                        imClient.close();
                    }
                }
            } else if (ImConstant.REQUEST_TYPE_SEND_MESSAGE == message.getRequestType()) {
                MessageResponseProto.MessageResponse messageResponse =
                        MessageResponseProto.MessageResponse.parseFrom(response.getBody());
                System.out.println("接收到用户"+messageResponse.getSenderId()+"的响应消息：" + messageResponse.getMessageId());
            } else if (ImConstant.REQUEST_TYPE_GROUP_MESSAGE == message.getRequestType()) {
                GroupMessageResponseProto.GroupMessageResponse messageResponse =
                        GroupMessageResponseProto.GroupMessageResponse.parseFrom(response.getBody());
                System.out.println("接收到用户"+messageResponse.getSenderId()+"的群聊响应消息：" + messageResponse.getMessageId());
            }
        } else if (ImConstant.MESSAGE_TYPE_REQUEST == message.getMessageType()) {
            Request request = message.toRequest();
            if (ImConstant.REQUEST_TYPE_PUSH_MESSAGE == message.getRequestType()) {
                PushMessageRequestProto.PushMessageRequest pushMessageRequest =
                        PushMessageRequestProto.PushMessageRequest.parseFrom(request.getBody());
                System.out.println("接收到用户"+pushMessageRequest.getSenderId()+"发送的消息：" + pushMessageRequest.getContent());
                sendPushMessageResponse(ctx, pushMessageRequest.getMessageId());
            } else if (ImConstant.REQUEST_TYPE_PUSH_GROUP_MESSAGE == message.getRequestType()) {
                PushGroupMessageRequestProto.PushGroupMessageRequest pushMessageRequest =
                        PushGroupMessageRequestProto.PushGroupMessageRequest.parseFrom(request.getBody());
                System.out.println("接收到用户"+pushMessageRequest.getSenderId()+"发送的群消息：" + pushMessageRequest.getContent());
                sendPushGroupMessageResponse(ctx, pushMessageRequest.getMessageId());
            }
        }
    }

    /**
     * 发送消息推送响应消息
     * @param ctx
     * @param messageId
     */
    private void sendPushMessageResponse(ChannelHandlerContext ctx, Long messageId) {
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        PushMessageResponseProto.PushMessageResponse.Builder builder =
                PushMessageResponseProto.PushMessageResponse.newBuilder();
        builder.setMessageId(messageId);
        Response response = new Response(ImConstant.APP_SDK_VERSION, ImConstant.REQUEST_TYPE_PUSH_MESSAGE,
                ImConstant.SEQUENCE_DEFAULT, builder.build().toByteArray());
        socketChannel.writeAndFlush(response.getBuf());
    }

    private void sendPushGroupMessageResponse(ChannelHandlerContext ctx, Long messageId) {
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        PushMessageResponseProto.PushMessageResponse.Builder builder =
                PushMessageResponseProto.PushMessageResponse.newBuilder();
        builder.setMessageId(messageId);
        Response response = new Response(ImConstant.APP_SDK_VERSION, ImConstant.REQUEST_TYPE_PUSH_MESSAGE,
                ImConstant.SEQUENCE_DEFAULT, builder.build().toByteArray());
        socketChannel.writeAndFlush(response.getBuf());
    }
}
